package org.dromara.common.core.utils;

import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.dromara.common.core.exception.ServiceException;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.stream.IntStream;

public class PdfUtils {
    /**
     * 校验pdf文件是否包含js脚本
     **/
    public static boolean containsJavaScript(byte[] input) {
        PDDocument document = null;
        try {
            document = Loader.loadPDF(input);
        } catch (IOException e) {
            //throw new ServiceException("检测pdf文件脚本失败");
            return false;
        }
        return containsJavaScript(document);
    }

    private static boolean containsJavaScript(PDDocument document) {
        if (document.getDocument().getTrailer().toString().contains("COSName{JS}")
            || document.getDocument().getTrailer().toString().contains("COSName{JavaScript}")){
            return true;
        }
        PDPageTree pages = document.getPages();
        return IntStream.range(0, pages.getCount()).anyMatch(i -> {
            String pageContent = pages.get(i).getCOSObject().toString();
            return pageContent.contains("COSName{JS}") ||pageContent.contains("COSName{JavaScript}") ;
        });
    }
}
